/**
 * @name: webSocket封装
 * @date: 2020.4.10
 */
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

var _this = new Vue();

const socket = new Vuex.Store({
	state: {
		link: null,
		timer: '',
		hasTimer: false
	},
	mutations: {
		//创建连接
		linkInit(state, token) {
			state.link = uni.connectSocket({
				url: _this.$api.socketUrl + '?token=' + token,
				complete: () => {}
			});
			state.link.onOpen(() => {
				console.log('连接已打开！');
				clearInterval(state.timer);

			});
			state.link.onClose(() => {
				console.log('连接已关闭！');
				this.dispatch('check');
			});
			state.link.onError(() => {
				console.log('连接打开失败，请检查！');
				clearInterval(state.timer)
				state.timer = setInterval(()=>{
					this.dispatch('check');
				},1000);
			});
			state.link.onMessage(obj => {
				let res = JSON.parse(obj.data);
				console.log(res);
				if(res.msgtype === "auth" && !res.data.success) {
					_this.$store.commit('logout');
					_this.$store.commit('showLogin', true);
				} else {
					uni.$emit('linkListen', res);
				}
			});
		},
		//发送数据
		linkSend(state, msg) {
			state.link.send({
				data: msg
			});
		},
		//关闭连接
		linkClose(state) {
			if(state.link) {
				state.link.close();
			}
		}
	},
    getters: {
        
    },
	actions: {
		init({ commit }) {
			let token = _this.$store.state.token;
			if(token) commit('linkInit', token);
		},
		send({ commit }, msg) {
			commit('linkSend', msg);
		},
		close({ commit }) {
			commit('linkClose');
		},
		//检测连接是否正常，closing 或 closed 状态下重新连接
		check({ commit }) {
			let token = _this.$store.state.token;
			if(token) {
				console.log(socket.state.link);
				if(!socket.state.link) {
					console.log(socket.state.link);
					commit('linkInit', token);
				} else {
					if(socket.state.link.readyState === 1) {
						clearInterval(socket.state.timer)
						console.log('已成功连接');
						// commit('linkSend', JSON.stringify({"msgtype":"ping","data":{"ping": 1}}));
					} else {
						console.log('重新初始化');
						commit('linkInit', token);
						clearInterval(socket.state.timer)
					}
				}
			}
		}
	}
})

Vue.prototype.$socket = socket;
